/**
 * Created by 小泽玛丽罗 on 2017/3/18.
 */
$(function () {

    $(".service").on("click",function(){
        var serviceId=$(this).attr("id");
        var url="serviceCost?serviceId="+serviceId;
        $.ajax({
            url:url,
            type:"get",
            success:function(data){
                console.info(data);
                var jsonObject=eval(data);
                var myChart = echarts.init(document.getElementById('chart'));
                serviceCostOption = {
                    title: {
                        text: '服务调用耗时',
                        subtext: ''
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:['调用耗时','最低气温']
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: {readOnly: false},
                            magicType: {type: ['line', 'bar']},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    xAxis:  {
                        type: 'category',
                        boundaryGap: false,
                        data: []
                    },
                    yAxis: {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value} ms'
                        }
                    },
                    series: [
                        {
                            name:'调用耗时',
                            type:'line',
                            data:jsonObject["caost"],
                            markPoint: {
                                data: [
                                    {type: 'max', name: '最大值'},
                                    {type: 'min', name: '最小值'}
                                ]
                            },
                            markLine: {
                                data: [
                                    {type: 'average', name: '平均值'}
                                ]
                            }
                        }
                    ]
                };
                myChart.setOption(serviceCostOption);
            },
            error:function(data){

            }
        });
        var ip=$(this).find(".ip").text();
        var port=$(this).find(".port").text();

        setDynamicChart(ip,port);
    });
    $("#serviceOptions").change(function () {
        var serviceType=$(this).val();
        var url=window.location.href;
        url=url.substring(0,url.indexOf("/")+1)+"service?serviceType="+serviceType;
        $(window.location).attr('href', url);
    })
    $(".serviceModal").on("click",function (event) {
        event.stopPropagation();
        $("#serviceModal").modal("show");
        var serviceId=$(this).val();
        $.ajax({
            url:"/getServiceNode?serviceId="+serviceId,
            type:"get",
            success:function (data) {
                $("#serviceName").val(data["serviceName"]);
                $("#serviceWeight").val(1);
                $("#serviceIp").val(data["ip"]);
                $("#servicePath").val(data["registerPath"]);
                $("#servicePort").val(data["port"]);
                $("#serviceModal").modal("show");
            }
        })
    });
    $(".serviceDownModal").on("click",function(event){
        event.stopPropagation();
        var serviceId=$(this).val();
        $("#serviceDownModal").modal("show");
    })
})

function setDynamicChart(ip,port){
    var metricsUrl="http://"+ip+":"+port+"/metrics";
    function randomData(dataValue) {
        now = new Date(+now + oneDay);
        return {
            name: new Date(),
            value: [
                [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/')+" "+now.getHours()+":"
                +now.getMinutes()+":"+now.getSeconds(),
                dataValue
            ]
        }
    }

    var classData = [];
    var heapData=[];
    var nonheapData=[];
    var memData=[];
    var threadData=[];
    var now = +new Date();
    var oneDay =  5000;

    var classChart = echarts.init(document.getElementById('classesChart'));
    var heapChart=echarts.init(document.getElementById("heapChart"));
    var nonheapChart=echarts.init(document.getElementById("nonheapChart"));
    var memChart=echarts.init(document.getElementById("memChart"));
    var threadCart=echarts.init(document.getElementById("threadChart"));
    option = {
        title: {
            text: '应用'+ip+'类加载数量信息 '
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                params = params[0];
                var date = new Date(params.name);
                return date.getHours()+'/'+date.getMinutes()+'/'+date.getSeconds()+" "+now.getHours()+":"
                    +now.getMinutes()+":"+now.getSeconds()+' : ' + params.value[1];
            },
            axisPointer: {
                animation: false
            }
        },
        xAxis: {
            type: 'time',
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            boundaryGap: ['40%', '40%'],
            splitLine: {
                show: false
            }
        },
        series: [{
            name: '类加载数量',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: classData
        }]
    };
    classChart.setOption(option);
    heapChart.setOption(option);
    nonheapChart.setOption(option);
    memChart.setOption(option);
    threadCart.setOption(option);
    heapChart.setOption({
        title: {
            text: '应用'+ip+'堆内存消耗信息（MB） '
        }
    });
    nonheapChart.setOption({
        title: {
            text: '应用'+ip+'非堆内存消耗信息（MB） '
        }
    });
    memChart.setOption({
        title: {
            text: '应用'+ip+'内存消耗信息（MB） '
        }
    });
    threadCart.setOption({
        title: {
            text: '应用'+ip+'活跃线程数量 '
        }
    })
    heapChart.setOption({
        series: [{
            name: '堆内存消耗',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: heapData
        }]
    });
    nonheapChart.setOption({
        series: [{
            name: '非堆内存消耗',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: nonheapData
        }]
    });
    memChart.setOption({
        series: [{
            name: '内存消耗',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: memData
        }]
    });
    threadCart.setOption({
        series: [{
            name: '线程数量',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: threadData
        }]
    });
    setInterval(function () {
        $.ajax({
            url:metricsUrl,
            type:"get",
            success:function(metricsData){
                if(classData.length>=250)
                    classData.shift();
                if(heapData.length>=250)
                    heapData.shift();
                if(nonheapData.length>=250)
                    nonheapData.shift();
                if(memData.length>=250)
                    memData.shift();
                if(threadData.length>=250)
                    threadData.shift();
                classData.push(randomData(metricsData["classes.loaded"]));
                var heapUsed=metricsData["heap.used"];
                heapUsed=parseInt(heapUsed/1024);
                var nonheapUsed=parseInt(metricsData["nonheap.used"]/1024);
                var memUsed=parseInt((metricsData["mem"]-metricsData["mem.free"])/1024);
                var threadNum=metricsData["threads"];
                heapData.push(randomData(heapUsed));
                nonheapData.push(randomData(nonheapUsed));
                memData.push(randomData(memUsed));
                threadData.push(randomData(threadNum));
                classChart.setOption({
                    series: [{
                        data: classData
                    }]
                });
                heapChart.setOption({
                    series: [{
                        data: heapData
                    }]
                });
                nonheapChart.setOption({
                    series: [{
                        data: nonheapData
                    }]
                });
                memChart.setOption({
                    series: [{
                        data: memData
                    }]
                });
                threadCart.setOption({
                    series: [{
                        data: threadData
                    }]
                })
            },
            error:function () {
                alert("获取"+ip+"应用信息失败");
            }
        })
    }, 5000);
}

